// pages/defect/adjustment/index.js
import {
  _list,
  _add,
  _update,
  _remove
} from '../../../api/defect-adjustment'
import {
  productList
} from '../../../api/setting'
import {
  PARAMS_TYPE
} from '../../../dataSource';

let ids = [];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataSource: [],
    products: [],
    _parent: {},
    disabledSwipe: false,
    addParamsShow: false,
    PARAMS_TYPE
  },
  toAdjust(event) {
    const {
      data 
    } = event.currentTarget.dataset;
 
    const ancestor = encodeURIComponent(JSON.stringify(this.data._parent)),
   
      grandfather = encodeURIComponent(JSON.stringify(data));
 
    wx.navigateTo({
      url: './tables/index?' + `ancestor=${ancestor}&grandfather=${grandfather}`,
    })
  },
  onSwipeDisabld(event) {
    // const len = event.currentTarget.dataset.length;
    // if (Number.parseInt(len) < 4) {
    //   return
    // }
    // this.setData({
    //   disabledSwipe: true
    // })
  },
  onSwipeEnable(event) {
    // const len = event.currentTarget.dataset.length;

    // if (Number.parseInt(len) < 4) {
    //   return
    // }
    // this.setData({
    //   disabledSwipe: false
    // })
  },
  onEdit(event) {
    const {
      index,
      item
    } = event.currentTarget.dataset;
    const dataSource = this.data.dataSource;
    wx.showModal({
      editable: true,
      title: '输入名称',
      placeholderText: '输入',
      content: item.name,
      success: res => {
        if (res.confirm) {
          if (res.content) {
            _update({
              ...item,
              name: res.content
            }, () => {
              dataSource[index] = {
                ...item,
                name: res.content
              }
              this.setData({
                dataSource
              })
            })
          } else {
            wx.showToast({
              title: '名称无效',
              icon: 'none'
            })
          }
        }
      }
    })
  },
  onAdd() {
 
     wx.navigateTo({
       url: '/pages/product-setting/index'
     })
  },
  onBack() {
    wx.navigateBack()
  },
  onDelect(event) {
    const dataSource = this.data.dataSource,
      index = event.currentTarget.dataset.index;
    wx.showModal({
      title: '确定要删除吗？',
      icon: 'none',
      success: res => {
        if (res.confirm) {
          _remove(dataSource[index], () => {
            dataSource.splice(index, 1);
            this.setData({
              dataSource
            })
          })
        }
      }
    })
  },
  async fetchData() {
    return new Promise((resolve, reject)=>{
    _list({
      adjustmentGlazeTypeId: this.data['_parent']['id']
    }, (res)=>{
      resolve(res);
       this.setData({
         dataSource: res
       })
    }, reject);
    })
  },
  fetchProductList(){
    productList({}, res => {
      this.setData({
        products: res
      })
    this.setDefectAdjustmentList(res)
    })
  },
 
  async onUpdateParams() {
    await this.fetchData();
    this.setDefectAdjustmentList(this.data.products)
  },
  onAddParamsCancel() {
    this.setData({
      addParamsShow: false
    })
  },
  onAddParamsShow() {
    this.setData({
      addParamsShow: true
    })
  },
  onAddParamsEdit(event) {
     const item = event.currentTarget.dataset.item;
     const instance = this.selectComponent('#_options');
     instance?.open(item);
  },
  onAddParamsSubmit(event) {
    _add({
      adjustmentGlazeTypeId: this.data['_parent']['id'],
      ...event.detail
    }, async () => {
      await this.fetchData();
      this.setDefectAdjustmentList(this.data.products);
    })
    this.onAddParamsCancel();
  },
  setDefectAdjustmentList(res) {
      const dataSource = this.data.dataSource.map(it => {
        return {
          ...it,
          _info: res.find(item => {
            return it.finishProductSettingsId === item.id
          }) || {}
        }
    })
     this.setData({
        dataSource
      })
      
  },
  onParamEdit(event) {
    // const {
    //   item,
    //   data
    // } = event.currentTarget.dataset;
    // const _optionsInstance = this.selectComponent("#_options");
    // _optionsInstance?.open(item, data)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    try {
      this.setData({
        _parent: JSON.parse(decodeURIComponent(options.data))
      })
      await this.fetchData();
      this.fetchProductList();
    } catch (e) {
      wx.navigateBack()
    }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})